package cn.com.homeyoda.aimate.aihealth.ui.game.play;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.lifecycle.ViewModelProviders;

import cn.com.homeyoda.aimate.aihealth.BR;
import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseActivity;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivityGamePlayBinding;
import cn.com.homeyoda.aimate.aihealth.ui.game.score.GameScoreActivity;
import com.google.android.flexbox.FlexboxLayout;
import com.google.android.material.button.MaterialButton;
import com.wzq.mvvmsmart.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class GamePlayActivity extends BaseActivity<ActivityGamePlayBinding, GamePlayViewModel> implements View.OnClickListener {

    private int currentPlay = 0;
    private final List<GamePlayBean> gamePlayList = new ArrayList<>();

    // 存放选项的id和对应的选项id
    private final Map<Integer, Set<Integer>> gamePlayMap = new HashMap<>();

    @Override
    public GamePlayViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(GamePlayViewModel.class);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_game_play;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initData() {
        super.initData();
        binding.ivBack.setOnClickListener(this);
        viewModel.getGamePlayData();
        initView();
    }

    private void initView() {
        binding.ivBack.setOnClickListener(this);
        binding.btnPre.setOnClickListener(this);
        binding.btnNext.setOnClickListener(this);
        setOptionView();
    }

    private void setPlayView() {
        GamePlayBean gamePlay = gamePlayList.get(currentPlay);
        boolean isSingleSelection = gamePlay.isSingleSelection();
        binding.tvTitle.setText(gamePlay.getTitle());
        binding.option1.setText(gamePlay.getOption1());
        binding.option1.setTag(isSingleSelection);
        binding.option2.setText(gamePlay.getOption2());
        binding.option2.setTag(isSingleSelection);
        binding.option3.setText(gamePlay.getOption3());
        binding.option3.setTag(isSingleSelection);
        binding.option4.setText(gamePlay.getOption4());
        binding.option4.setTag(isSingleSelection);
        binding.tvChoiceType.setText(isSingleSelection ? "单选" : "多选");
        binding.tvProgress.setText(currentPlay + 1 + "/" + gamePlayList.size());
        setProgress();
    }

    private void setProgress() {
        int size = gamePlayList.size();
        Set<Integer> curtSelectedSet = gamePlayMap.get(currentPlay);
        double progress;
        if (curtSelectedSet == null || curtSelectedSet.isEmpty()) {
            progress = (double) currentPlay / size;
        } else {
            progress = (double) (currentPlay + 1) / size;
        }
        binding.pb.setProgress((int) (progress * 100));
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.gamePlayData.observe(this, list -> {
            gamePlayList.clear();
            gamePlayList.addAll(list);
            setPlayView();
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.btn_pre) {
            if (currentPlay <= 0) {
                return;
            }
            currentPlay--;
            restorePreviousSelection();
            setPlayView();
        } else if (id == R.id.btn_next) {
            Set<Integer> curtSelectedSet = gamePlayMap.get(currentPlay);
            if (curtSelectedSet == null || curtSelectedSet.isEmpty()) {
                ToastUtils.showShort("请选择您的回答");
                return;
            }
            if (currentPlay >= gamePlayList.size() - 1) {
                startActivity(new Intent(this, GameScoreActivity.class));
                finish();
                return;
            }
            currentPlay++;
            Set<Integer> selectedSet = gamePlayMap.get(currentPlay);
            if (selectedSet == null) {
                clearSelection();
            } else {
                restorePreviousSelection();
            }
            setPlayView();
        }
    }

    private void restorePreviousSelection() {
        Set<Integer> selectedSet = gamePlayMap.get(currentPlay);
        if (selectedSet == null) {
            return;
        }
        for (int i = 0; i < binding.flexboxLayout.getChildCount(); i++) {
            View child = binding.flexboxLayout.getChildAt(i);
            if (child instanceof MaterialButton) {
                MaterialButton button = (MaterialButton) child;
                button.setChecked(selectedSet.contains(button.getId()));
            }
        }
    }

    private void clearSelection() {
        for (int i = 0; i < binding.flexboxLayout.getChildCount(); i++) {
            View child = binding.flexboxLayout.getChildAt(i);
            if (child instanceof MaterialButton) {
                ((MaterialButton) child).setChecked(false);
            }
        }
    }

    private void setOptionView() {
        FlexboxLayout flexboxLayout = findViewById(R.id.flexboxLayout);

        for (int i = 0; i < flexboxLayout.getChildCount(); i++) {
            View child = flexboxLayout.getChildAt(i);
            if (child instanceof MaterialButton) {
                child.setOnClickListener(view -> {
                    Set<Integer> selectedSet = gamePlayMap.get(currentPlay);
                    if (selectedSet == null) {
                        selectedSet = new HashSet<>();
                    }
                    if ((boolean) view.getTag()) {
                        // 单选
                        for (int j = 0; j < flexboxLayout.getChildCount(); j++) {
                            View btn = flexboxLayout.getChildAt(j);
                            if (btn instanceof MaterialButton) {
                                MaterialButton button = (MaterialButton) btn;
                                button.setChecked(btn == view); // 只允许当前点击的按钮被选中
                                if (button.isChecked()) {
                                    selectedSet.add(button.getId());
                                } else {
                                    selectedSet.remove(button.getId());
                                }
                            }
                        }
                    } else {
                        // 多选
                        MaterialButton button = (MaterialButton) view;
                        if (button.isChecked()) {
                            selectedSet.add(button.getId());
                        } else {
                            selectedSet.remove(button.getId());
                        }
                    }
                    gamePlayMap.put(currentPlay, selectedSet);
                    setProgress();
                });
            }
        }
    }

}